package info.rongtong.service.basic;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public abstract class BasicServiceImpl implements BasicServiceInter {

	// 使用注释标记，自动使用byName的方式装配bean
	@Resource
	private SessionFactory sessionFactory;
	Logger log = Logger.getLogger(this.getClass());
	public <T> void delObjectById(Class<T> clazz, Serializable id) {
		// 由于hibernate删除是需要的是一个对象，所以我们可以先获取到该对象，再进行删除操作
		T t = this.findObjectById(clazz, id);
		sessionFactory.getCurrentSession().delete(t);
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public <T> List<T> executeQuery(final Class<T> clazz,final String hql,
			final Object[] parameters) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		if (parameters != null) {
			for (int i = 0; i < parameters.length; i++) {
				query.setParameter(i, parameters[i]);
			}
		}
		return query.list();
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> executeQuery(final Class<T> clazz,final String hql,
			final Object[] parameters,final int pageNow,final int pageSize) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		if (parameters != null) {
			for (int i = 0; i < parameters.length; i++) {
				query.setParameter(i, parameters[i]);
			}
		}
		return query.setFirstResult((pageNow - 1) * pageSize).setMaxResults(
				pageSize).list();
	
	}

	@SuppressWarnings("unchecked")
	public void exeuteUpdate(final String hql, Object[] obj) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		if (obj != null && obj.length > 0) {
			for (int i = 0; i < obj.length; i++) {
				query.setParameter(i, obj[i]);
			}
		}
		query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public <T> T findObjectById(Class<T> clazz, Serializable id) {
		T t = (T) sessionFactory.getCurrentSession().get(clazz, id);
		return t;
	}

	public int queryPageCount(String hql, int pageSize) {
		Integer count = Integer.parseInt(this.uniqueResult(hql, null)
				.toString());
		return (count - 1) / pageSize + 1;
	}
	
	public void saveOrUpdate(Object object) {
		sessionFactory.getCurrentSession().saveOrUpdate(object);
	}

	public Object uniqueResult( String hql, Object[] parameters) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		if (parameters != null && parameters.length > 0) {
			for (int i = 0; i < parameters.length; i++) {
				query.setParameter(i, parameters[i]);
			}
		}
		return query.uniqueResult();
	}


}
